package com.qf.fc.aop;

import cn.hutool.core.date.DateUtil;

import com.qf.fc.anno.MyLog;
import com.qf.fc.dao.UserLogDao;
import com.qf.fc.entity.UserLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.aspectj.lang.reflect.MethodSignature;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @version 1.0
 * @Author zhangH
 * @Date 2024/12/21 11:50
 */
@Component
@Slf4j
@Aspect
public class RecordOperateLog {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserLogDao userLogDao;

    // 采用环绕通知，记录日志
    @Around("@annotation(com.qf.fc.anno.MyLog)")
    public Object logRecord(ProceedingJoinPoint joinPoint) throws Throwable {

        // 调用原始目标方法运行
        Object result = joinPoint.proceed();

        // 记录操作日志
        UserLog userLog = new UserLog();

        userLog.setType(request.getMethod());
        userLog.setContent(String.valueOf(joinPoint.proceed()));
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
        userLog.setCreateTime(DateUtil.parseDateTime(format));
        userLogDao.insert(userLog);
        log.info("Aop记录操作日志：{}",userLog);
        return result;
    }
    @Around("execution(* com.qf.fc.controller..*.*(..))")
    public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        log.info(joinPoint.getSignature().getName()+"方法执行，耗时：{}ms",end-start);
        return result;

    }
}
